package xyz.jcat.spring.security.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import xyz.jcat.common.web.Resp;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.web.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthenticationRestHandler implements AuthenticationSuccessHandler,
        AuthenticationFailureHandler, LogoutSuccessHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.debug("登录失败。。。");
        WebUtils.writeJson(response, Resp.fail(RespCodeMsg.ACCOUNT_OR_PWD_ERROR));
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("登录成功。。。");
        UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        LoginUserInfo loginUserInfo = new LoginUserInfo();
        loginUserInfo.setUsername(userDetails.getUsername());
        WebUtils.writeJson(response, Resp.ok(loginUserInfo));
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("退出登录。。。");
        WebUtils.writeJson(response, Resp.ok());
    }
}
